﻿using System;
namespace TestServices
{
    using System;
    using System.Collections.Generic;

    /// <summary>
    /// An implementation of IServiceProvider that uses a dictionary
    /// </summary>
    public class ServiceProvider : IServiceProvider
    {
        private readonly Dictionary<Type, object> services = new Dictionary<Type, object>();

        public ServiceProvider()
        {
        }

        #region IServiceProvider Members

        /// <summary>
        /// Returns the specified service or null if the service doesn't exist.
        /// </summary>
        /// <param name="serviceType"></param>
        /// <exception cref="ArgumentNullException"></exception>
        /// <returns></returns>
        public object GetService(Type serviceType)
        {
            // <pex>
            if (serviceType == (Type)null)
            {
                throw new ArgumentNullException("serviceType");
            }
            // </pex>
            object service = null;
            services.TryGetValue(serviceType, out service);
            return service;
        }

        #endregion

        #region Public API

        /// <summary>
        /// Adds a service to the service provider's list of services using the object's type as the key.
        /// </summary>
        /// <param name="service"></param>
        /// <exception cref="ArgumentNullException"></exception>
        public void AddService(object service)
        {
            // <pex>
            if (service == null)
            {
                throw new ArgumentNullException("service");
            }
            // </pex>
            services.Add(service.GetType(), service);
        }

        /// <summary>
        /// Adds a service to the service provider's list of services using the provided Type as the key.
        /// </summary>
        /// <param name="baseType"></param>
        /// <param name="service"></param>
        /// <exception cref="ArgumentNullException"></exception>
        public void AddService(Type baseType, object service)
        {
            // <pex>
            if (baseType == (Type)null)
            {
                throw new ArgumentNullException("baseType");
            }
            // </pex>
            services.Add(baseType, service);
        }

        #endregion
    }
}